package com.example.erhuo.activity;

import androidx.annotation.NonNull;
import androidx.appcompat.app.ActionBar;
import androidx.appcompat.app.AlertDialog;
import androidx.appcompat.app.AppCompatActivity;

import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.view.MenuItem;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;

import com.example.erhuo.R;
import com.example.erhuo.api.NetAPI;

import org.json.JSONException;
import org.json.JSONObject;

import java.io.IOException;

import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.FormBody;
import okhttp3.RequestBody;
import okhttp3.Response;
import okhttp3.ResponseBody;

public class RegisterActivity extends AppCompatActivity implements View.OnClickListener {

    private EditText nameEditText;
    private EditText nicknameEditText;
    private EditText emailEditText;
    private EditText passwordFirstEditText;
    private EditText passwordSecondEditText;
    private EditText wechatEdit;
    private EditText qqEdit;

    private String name = null;
    private String nickname = null;
    private String email = null;
    private String passwordFirst = null;
    private String passwordSecond = null;
    private String wechat;
    private String qq;

    private Button buttonSure;

    private static String TAG = "RegisterActivity";

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        ActionBar actionBar = getSupportActionBar();
        if (actionBar != null) {
            actionBar.setDisplayOptions(ActionBar.DISPLAY_SHOW_CUSTOM);
            actionBar.setCustomView(R.layout.title_layout);
            TextView textView = (TextView) actionBar.getCustomView().findViewById(R.id.display_title);
            textView.setText("注册");
            actionBar.setHomeButtonEnabled(true);
            actionBar.setDisplayHomeAsUpEnabled(true);
            actionBar.setDisplayShowCustomEnabled(true);
        }
        setContentView(R.layout.activity_register);

        nameEditText = findViewById(R.id.register_edit_name);//这是学号
        nicknameEditText = findViewById(R.id.register_edit_nickname);
        emailEditText = findViewById(R.id.register_edit_email);
        wechatEdit = findViewById(R.id.register_edit_wechat);
        qqEdit = findViewById(R.id.register_edit_qq);
        passwordFirstEditText = findViewById(R.id.register_edit_pwd_old);
        passwordSecondEditText = findViewById(R.id.register_edit_pwd_new);
        buttonSure = findViewById(R.id.register_btn_sure);

        buttonSure.setOnClickListener(this);

    }

    @Override
    public void onClick(View v) {
        //Log.i(TAG, "" + v.getId());
        switch (v.getId()) {
            case R.id.register_btn_sure:
                name = nameEditText.getText().toString();
                nickname = nicknameEditText.getText().toString();
                email = emailEditText.getText().toString();
                passwordFirst = passwordFirstEditText.getText().toString();
                passwordSecond = passwordSecondEditText.getText().toString();
                wechat = wechatEdit.getText().toString();
                qq = qqEdit.getText().toString();
                if (hasEmpty()) {
                    sendAlertDialog("不能为空!", "请填写全部注册信息");
                    break;
                }
                if (isPasswordDifferent()) {
                    sendAlertDialog("密码不同!", "请确保两次密码相同");
                    break;
                }
                if (passwordFirst.length() < 6 || passwordFirst.length() > 20) {
                    sendAlertDialog("密码长度错误！", "请保证密码长度在6-20位");
                    break;
                }
                if (isEmailFormWrong()) {
                    sendAlertDialog("邮箱格式错误!", "请检查邮箱格式");
                    break;
                }
                // send information
                RequestBody body = new FormBody.Builder()
                        .add("username", name)
                        .add("password1", passwordFirst)
                        .add("password2", passwordSecond)
                        .add("name", nickname)
                        .add("email", email)
                        .add("qq",qq)
                        .add("wechat",wechat)
                        .add("sex", "0")
                        .build();
                Log.i(TAG, "username:" + name);
                Callback callback = new Callback() {
                    @Override
                    public void onFailure(@NonNull Call call, @NonNull IOException e) {
                        Log.e(TAG, "注册请求异常");
                        Log.e(TAG, e.toString());
                        runOnUiThread(new Runnable() {
                            @Override
                            public void run() {
                                Toast.makeText(getApplicationContext(), "网络连接超时，请检查网络后重试", Toast.LENGTH_SHORT).show();
                            }
                        });
                    }

                    @Override
                    public void onResponse(@NonNull Call call, @NonNull Response response) throws IOException {
                        String information = response.body().string();
                        Log.i(TAG, information);
                        JSONObject json = null;
                        try {
                            json = new JSONObject(information);
                            String msg = json.getString("msg");
                            Log.i(TAG, msg);
                            if (msg.equals("创建成功，请前往邮箱" + email + "进行验证")) {
                                runOnUiThread(new Runnable() {
                                    @Override
                                    public void run() {
                                        sendAlertDialog("创建成功，请前往邮箱" + email + "进行验证", "");
                                    }
                                });
                            }
                            switch (msg) {
                                case "该学号已被注册，但还没有经过邮箱激活": {
                                    //该学号已被注册，但还没有经过邮箱激活
                                    runOnUiThread(new Runnable() {
                                        @Override
                                        public void run() {
                                            AlertDialog.Builder builder = new AlertDialog.Builder(RegisterActivity.this);
                                            builder.setTitle("邮箱未激活");
                                            builder.setMessage("该学号已注册，但邮箱未激活\n" +
                                                    "请登录" + email + "完成邮箱验证\n" +
                                                    "若未收到邮箱，请点击重新发送");
                                            builder.setNegativeButton("取消", null);
                                            builder.setPositiveButton("重新发送", new DialogInterface.OnClickListener() {
                                                @Override
                                                public void onClick(DialogInterface dialog, int which) {
                                                    RequestBody body1 = new FormBody.Builder()
                                                            .add("username", name)
                                                            .build();
                                                    Callback callback1 = new Callback() {
                                                        @Override
                                                        public void onFailure(@NonNull Call call, @NonNull IOException e) {
                                                            Log.e(TAG, "重新发送邮件异常");
                                                        }

                                                        @Override
                                                        public void onResponse(@NonNull Call call, @NonNull Response response) throws IOException {
                                                            String information = response.body().string();
                                                            Log.i(TAG, information);
                                                            JSONObject json = null;
                                                            try {
                                                                json = new JSONObject(information);
                                                                String msg = json.getString("msg");
                                                                Log.i(TAG, msg);
                                                                switch (msg) {
                                                                    case "发送成功":
                                                                        runOnUiThread(new Runnable() {
                                                                            @Override
                                                                            public void run() {
                                                                                Toast.makeText(getApplicationContext(), "邮件发送成功，请登陆北航邮箱验证", Toast.LENGTH_SHORT).show();
                                                                                buttonSure.setClickable(false);
                                                                                Handler mHandler = new Handler() {
                                                                                    @Override
                                                                                    public void handleMessage(Message msg) {
                                                                                        // TODO Auto-generated method stub
                                                                                        super.handleMessage(msg);
                                                                                    }

                                                                                };
                                                                                mHandler.sendEmptyMessageDelayed(0, 2000);
                                                                                buttonSure.setClickable(true);
                                                                            }
                                                                        });
                                                                        break;
                                                                    case "该账号已经成功激活，不需要邮箱验证":
                                                                        Intent intent = new Intent(RegisterActivity.this, LoginActivity.class);
                                                                        startActivity(intent);
                                                                        break;
                                                                }
                                                            } catch (JSONException e) {
                                                                e.printStackTrace();
                                                            }
                                                        }
                                                    };
                                                    NetAPI.postJson("api/register/verify/", body1, callback1);
                                                }
                                            });
                                            builder.show();
                                        }
                                    });
                                    break;
                                }
                                case "学号已被注册": {
                                    runOnUiThread(new Runnable() {
                                        @Override
                                        public void run() {
                                            sendAlertDialog("该学号已被注册！", "");
                                        }
                                    });
                                    break;
                                }
                                case "昵称已经存在": {
                                    runOnUiThread(new Runnable() {
                                        @Override
                                        public void run() {
                                            sendAlertDialog("该昵称已被注册！", "");
                                        }
                                    });
                                    break;
                                }
                            }
                        } catch (JSONException e) {
                            e.printStackTrace();
                        }
                    }
                };
                NetAPI.postJson("api/register/", body, callback);
                break;
        }
    }

    private boolean hasEmpty() {
        if (nickname == null || nickname.equals("")) {
            return true;
        }
        if (email == null || email.equals("")) {
            return true;
        }
        if (passwordFirst == null || passwordFirst.equals("")) {
            return true;
        }
        if (passwordSecond == null || passwordSecond.equals("")) {
            return true;
        }
        return false;
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        switch (item.getItemId()) {
            case android.R.id.home:
                this.finish();
                return true;
        }
        return super.onOptionsItemSelected(item);
    }

    private boolean isPasswordDifferent() {
        return !passwordFirst.equals(passwordSecond);
    }

    private boolean isEmailFormWrong() {
        return !email.matches("\\w+([-+.]\\w+)*@\\w+([-.]\\w+)*\\.\\w+([-.]\\w+)*");
    }

    private void sendAlertDialog(String title, String message) {
        AlertDialog.Builder builder = new AlertDialog.Builder(RegisterActivity.this);
        builder.setTitle(title);
        builder.setMessage(message);
        builder.setPositiveButton("好的", null);
        builder.show();
    }


}